<template>
  <el-card style="max-width: 100%">
    <el-alert
      title="注意：只允许为第三级分类设置相关参数"
      type="warning"
      center
      show-icon
      :closable="false"
    />
    <el-row class="cat_top">
      <el-col>
        <span class="cat_right">选择商品分类</span>
        <el-cascader
          expand-trigger="hover"
          v-model="selectedCateKeys"
          :options="categoriesList"
          :props="cateprop"
          @change="handleChange"
          placeholder="请选择商品分类"
        />
      </el-col>
    </el-row>
    <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleTabClick">
      <el-tab-pane label="动态参数" name="many"
        ><el-button
          class="cat_top"
          type="primary"
          size="large"
          :disabled="isBtnDisabled"
          @click="changedialogVisible()"
          >添加参数</el-button
        >
        <el-table :data="manyTableDATA" border stripe>
          <el-table-column type="expand">
            <template #default="row">
              <el-tag
                class="index-tag"
                v-for="(item, index) in row.row.attr_vals"
                :key="index"
                closable
              >
                {{ item }}
              </el-tag>
              <el-input
                v-if="row.row.inputVisible"
                ref="InputRef"
                v-model="row.row.inputValue"
                class="w-20"
                size="small"
                @keyup.enter="taghandleInputConfirm(row.row)"
                @blur="taghandleInputConfirm(row.row)"
              />
              <el-button
                v-else
                class="index-tag"
                size="small"
                @click="showInput(row.row)"
              >
                添加新标签
              </el-button>
            </template>
          </el-table-column>
          <el-table-column label="参数名" prop="attr_name" />
          <el-table-column label="操作" prop="attr_name">
            <template #default="row">
              <el-tooltip
                class="box-item"
                effect="dark"
                content="编辑"
                placement="top"
                :enterable="false"
              >
                <el-button
                  type="primary"
                  size="default"
                  :icon="Edit"
                  @click="handleDialogValue(row)"
                  >编辑</el-button
                >
              </el-tooltip>
              <el-tooltip
                class="box-item"
                effect="dark"
                content="删除"
                placement="top"
                :enterable="false"
              >
                <el-button
                  type="danger"
                  size="default"
                  :icon="Delete"
                  @click="Editdelete(row)"
                  >删除</el-button
                >
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table></el-tab-pane
      >
      <el-tab-pane label="静态属性" name="only"
        ><el-button
          class="cat_top"
          type="primary"
          size="large"
          :disabled="isBtnDisabled"
          @click="changedialogVisible()"
          >添加属性</el-button
        >
        <el-table :data="onlyTableDATA" border stripe>
          <el-table-column type="expand" />
          <el-table-column label="参数名" prop="attr_name" />
          <el-table-column label="操作" prop="attr_name">
            <template #default="row">
              <el-tooltip
                class="box-item"
                effect="dark"
                content="编辑"
                placement="top"
                :enterable="false"
              >
                <el-button
                  type="primary"
                  size="default"
                  :icon="Edit"
                  @click="handleDialogValue(row)"
                  >编辑</el-button
                >
              </el-tooltip>
              <el-tooltip
                class="box-item"
                effect="dark"
                content="删除"
                placement="top"
                :enterable="false"
              >
                <el-button
                  type="danger"
                  size="default"
                  :icon="Delete"
                  @click="Editdelete(row)"
                  >删除</el-button
                >
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table></el-tab-pane
      >
    </el-tabs>
  </el-card>
  <el-dialog
    v-model="dialogVisible"
    :title="'添加' + title"
    width="500px"
    :before-close="handleClose"
    @close="handleCloseDialog()"
  >
    <el-form
      :model="addForm"
      label-width="auto"
      style="max-width: 600px"
      :rules="addFormRules"
      ref="addFormRef"
    >
      <el-form-item :label="title" prop="attr_name">
        <el-input v-model="addForm.attr_name" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="addParams()"> 确认 </el-button>
      </div>
    </template>
  </el-dialog>
  <el-dialog
    v-model="EditdialogVisible"
    :title="'修改' + title"
    width="500px"
    :before-close="handleClose"
    @close="EdithandleCloseDialog()"
  >
    <el-form
      :model="EditaddForm"
      label-width="auto"
      style="max-width: 600px"
      :rules="EditaddFormRules"
      ref="EditaddFormRef"
    >
      <el-form-item :label="title" prop="attr_name">
        <el-input v-model="EditaddForm.attr_name" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="Editclear">取消</el-button>
        <el-button type="primary" @click="EditaddParams()"> 确认 </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import {
  getCategories,
  getCategory,
  getCategorieset,
  addCategory,
  deleteCategory,
  selectCategory,
  addTagAttrVals
} from '@/api/categories'
import { ref, computed, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { useI18n } from 'vue-i18n'
const i18n = useI18n()
const EditdialogVisible = ref(false)
const EditaddForm = ref({
  attr_name: ''
})
const EditaddFormRules = ref({
  attr_name: [{ required: true, message: '请输入名字', trigger: 'blur' }]
})
const EditaddFormRef = ref(null)
const EdithandleCloseDialog = () => {
  return null
}
const handleDialogValue = async (arrtid) => {
  console.log(arrtid.row.attr_id)
  const res = await selectCategory(
    cateId.value,
    arrtid.row.attr_id,
    activeName.value
  )
  EditaddForm.value = res
  EditdialogVisible.value = true
}
const Editclear = () => {
  EditdialogVisible.value = false
}
const Editdelete = async (row) => {
  console.log(row.row)
  await deleteCategory(cateId.value, row.row.attr_id)
  ElMessage({
    message: i18n.t('message.updeteSuccess'),
    type: 'success'
  })
  getParamsData()
}
const EditaddParams = () => {
  EditaddFormRef.value.validate(async (valid) => {
    if (!valid) {
      return
    }
    await addCategory(
      cateId.value,
      EditaddForm.value.attr_id,
      EditaddForm.value.attr_name,
      EditaddForm.value.attr_sel
    )
    ElMessage({
      message: i18n.t('message.updeteSuccess'),
      type: 'success'
    })
    getParamsData()
    EditdialogVisible.value = false
  })
}
const categoriesList = ref([])
const cateprop = ref({
  value: 'cat_id',
  label: 'cat_name',
  children: 'children'
})
const dialogVisible = ref(false)
const selectedCateKeys = ref([])
const activeName = ref('many')
const manyTableDATA = ref([])
const onlyTableDATA = ref([])
const addForm = ref({
  attr_name: ''
})
const addFormRules = ref({
  attr_name: [{ required: true, message: '请输入名字', trigger: 'blur' }]
})
const addFormRef = ref(null)
const getCategoriesList = async () => {
  const res = await getCategories()
  categoriesList.value = res
}
getCategoriesList()
const getParamsData = async () => {
  if (selectedCateKeys.value.length !== 3) {
    selectedCateKeys.value = []
    manyTableDATA.value = []
    onlyTableDATA.value = []
    return
  }
  const res = await getCategory(cateId.value, activeName.value)
  console.log(res)
  res.forEach((element) => {
    element.attr_vals = element.attr_vals ? element.attr_vals.split(' ') : []
    element.inputVisible = false
    element.inputValue = ''
    console.log(element)
  })
  console.log(333)
  if (activeName.value === 'many') {
    manyTableDATA.value = res
  } else {
    onlyTableDATA.value = res
  }
}
const handleChange = () => {
  getParamsData()
}
const handleTabClick = () => {
  getParamsData()
}
const isBtnDisabled = computed(() => {
  return selectedCateKeys.value.length !== 3
})
const cateId = computed(() => {
  if (selectedCateKeys.value.length !== 3) {
    return null
  }
  return selectedCateKeys.value[2]
})
const title = computed(() => {
  if (activeName.value === 'many') {
    return '动态参数'
  } else {
    return '静态参数'
  }
})
const changedialogVisible = () => {
  dialogVisible.value = true
}
const handleCloseDialog = () => {
  addFormRef.value.resetFields()
}
const addParams = () => {
  addFormRef.value.validate(async (valid) => {
    if (!valid) {
      return
    }
    await getCategorieset(
      cateId.value,
      addForm.value.attr_name,
      activeName.value
    )
    dialogVisible.value = false
    ElMessage({
      message: i18n.t('message.updeteSuccess'),
      type: 'success'
    })
    getParamsData()
  })
}
const taghandleInputConfirm = async (row) => {
  if (row.inputValue.trim().length === 0) {
    row.inputVisible = false
    row.inputValue = ''
    return
  }
  row.attr_vals.push(row.inputValue.trim())
  row.inputValue = ''
  row.inputVisible = false
  await addTagAttrVals(
    cateId.value,
    row.attr_id,
    row.attr_name,
    activeName.value,
    row.attr_vals.join(' ')
  )
  ElMessage({
    message: i18n.t('message.updeteSuccess'),
    type: 'success'
  })
}
const showInput = (row) => {
  console.log(222)
  row.inputVisible = true
  nextTick(() => {
    // 自动获取焦点
    // this.$refs.InputRef[row.rowIndex].focus()
  })
}
</script>

<style lang="scss" scoped>
.cat_top {
  margin: 35px;
}
.cat_right {
  margin-right: 20px;
}
.index-tag {
  margin: 40px;
  font-size: 15px;
}
.w-20 {
  width: 120px;
  margin: 40px;
  font-size: 15px;
}
</style>
